module GroParser

using Printf
using Structure

export gen_gro_from_file, to_gro
export GRO

mutable struct GRO
    title::String
    atom_num::Int32
    atoms::Vector{GeneralAtom}
    box::Vector{Float64}
end

function gen_gro_from_file(filename::AbstractString)
    lines = readlines(filename)
    # 处理title
    title = lines[1]
    atom_num = parse(Int32, lines[2])
    # 处理坐标
    atoms = Vector{GeneralAtom}()
    for line in lines[3:2 + atom_num]
        push!(atoms, gen_atom_from_line(line))
    end
    # 处理盒子
    box = parse.(Float64, split(lines[3 + atom_num]))
    return GRO(title, atom_num, atoms, box)
end

function gen_atom_from_line(atomline::AbstractString)
    resid = parse(Int32, atomline[1:5])
    resname = strip(atomline[6:8])
    atname = strip(atomline[9:15])
    atid = parse(Int32, atomline[16:20])
    x = parse(Float64, strip(atomline[21:28]))
    y = parse(Float64, strip(atomline[29:36]))
    z = parse(Float64, strip(atomline[37:44]))
    if length(atomline) > 44
        vx = parse(Float64, strip(atomline[45:52]))
        vy = parse(Float64, strip(atomline[53:60]))
        vz = parse(Float64, strip(atomline[61:68]))
    else
        vx = 0
        vy = 0
        vz = 0
    end
    return GeneralAtom(; resid=resid, resname=resname, atname=atname, atid=atid, x=x, y=y, z=z, vx=vx, vy=vy, vz=vz)
end

function to_gro(gro::GRO, gro_file::AbstractString)
    gro_file = open(gro_file, "w")
    write(gro_file, gro.title * ", Created by SuperMDA (https://gitee.com/supernova_bingbing/SuperMDA)\n")
    write(gro_file, "$(gro.atom_num)\n")
    for atom in gro.atoms
        write(gro_file, to_str_gro(atom))
    end
    (coord -> write(gro_file, @sprintf("%10.5f", coord))).(gro.box)
    write(gro_file, "\n")
    close(gro_file)
end

end # module
